(function(){
  'use strict';

  if (!window.Api) return;

  var currentScript = null;
  var subModal = document.getElementById('sub-modal');
  var subAccount = document.getElementById('sub-account');
  var subAmount = document.getElementById('sub-amount');
  var subMsg = document.getElementById('sub-msg');
  var subCancel = document.getElementById('sub-cancel');
  var subConfirm = document.getElementById('sub-confirm');

  async function populateAccountsSelect(){
    if (!subAccount) return;
    subAccount.innerHTML='';
    try {
      var mt = (currentScript && currentScript.market_type) || '';
      var path = '/users/connectors' + (mt ? ('?market_type=' + encodeURIComponent(mt)) : '');
      var res = await window.Api.request('GET', path, null, true);
      var data = await window.Api.jsonOrThrow(res);
      var connectors = (data && data.connectors) || (Array.isArray(data) ? data : []);
      if (!Array.isArray(connectors) || !connectors.length){
        var opt0=document.createElement('option'); opt0.textContent='未绑定任何交易所'; subAccount.appendChild(opt0); return;
      }
      connectors.forEach(function(name){ var opt=document.createElement('option'); opt.value=name; opt.textContent=name; subAccount.appendChild(opt); });
    } catch (_) {
      var optx=document.createElement('option'); optx.textContent='加载失败'; subAccount.appendChild(optx);
    }
  }

  window.openSubscribeModal = async function(script){
    currentScript = script || null;
    if (!currentScript) return;
    if (subMsg) subMsg.textContent='';
    if (subAmount) subAmount.value='';
    await populateAccountsSelect();
    if (subModal) subModal.classList.remove('is-hidden');
  };

  function closeModal(){ if (subModal) subModal.classList.add('is-hidden'); }
  if (subCancel) subCancel.addEventListener('click', closeModal);

  if (subConfirm){
    subConfirm.addEventListener('click', async function(){
      if (!currentScript) return;
      var pct = parseFloat(subAmount && subAmount.value ? subAmount.value : '0');
      if (isNaN(pct) || pct <= 0 || pct > 100){ if (subMsg) subMsg.textContent='请输入 0-100 之间的投入比例(%)'; return; }
      var connectorName = subAccount && subAccount.value ? subAccount.value : '';
      var accountNameEl = document.getElementById('bind-account');
    var payload = {
        script_id: currentScript.id,
      enabled: true,
        allocation: { mode: 'percent_of_equity', value: pct },
        connector_name: connectorName,
        account_name: (accountNameEl && accountNameEl.value) || ''
    };
    try {
        var res = await window.Api.request('POST','/subscriptions',payload,true);
        await window.Api.jsonOrThrow(res);
        if (subMsg) subMsg.textContent='订阅成功';
        setTimeout(function(){ closeModal(); if (typeof window.loadMarket === 'function') window.loadMarket(); }, 600);
      } catch (err){
        if (subMsg) subMsg.textContent='失败：' + (err && err.message ? err.message : '未知错误');
      }
    });
  }
})();

